/*
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    '../../../common/service',
    'text!../tpl/simpleElement.html',
    'text!../tpl/elementGroup.html'
], function(
    http,
    tpl,
    elementGroupTpl
) {
    function SimpleElement() {
        var self = this;
        this.init = function(templateId, callback) {
            self.templateId = templateId;
            self.callback = callback;
            self.smallCategory = null;
            self.$root = $('#tab-content0');

            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl, 'templateDetail'));
            self.$elementContainer = self.$root.find('.element-result-container');
            self.initSelect();
            self.event();
        }

        this.event = function() {
            self.getElementSmallCategory();
            //modal打开先请求元素数据
            self.$root.find('#search-area .btn-primary').off('click').on('click', $.proxy(self.openAddElementDialog, self));
            $('#uploadSimpleEle').change(function() {
                self.uploadSimpleEle();
            });

        }

        /**
         * 获取元素二级分类
         */
        this.getElementSmallCategory = function() {
            var param = {
                elementType: self.$root.find('input[name="elementType"]').attr('data-val') || 0
            }
            http.work('/ectemplatedetail/getElementSmallCategory', param, 'POST').then(function(res) {
                if (res.succeed) {
                    self.smallCategory = res.data;
                    self.filterFindElements();
                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        this.initSelect = function() {
            $("div.ndp-drop-wrapper[name=inline-drop1]").drop({
                data: [{
                    value: '0',
                    text: I18N.getText('templateDetail', 'allElementLevel')
                }, {
                    value: 'F',
                    text: I18N.getText('templateDetail', 'mainStyle')
                }, {
                    value: 'S',
                    text: I18N.getText('templateDetail', 'helpStyle')
                }],
                name: "elementLevel"
            }).on("ITEM_CLICK", function(e) {
                self.filterFindElements();
            }).val({
                value: '0',
                text: I18N.getText('templateDetail', 'allElementLevel')
            });

            var elementTypeArr = [{
                value: '0',
                text: I18N.getText('templateDetail', 'allElementType')
            }];
            http.work('/ectemplatedetail/getElementBigCategory', null, 'POST').then(function(res) {
                if (res.succeed) {
                    $.each(res.data, function(i, v) {
                        elementTypeArr.push({
                            value: v.id,
                            text: v.name
                        });
                    });
                    $("div.ndp-drop-wrapper[name=inline-drop2]").empty().drop({
                        data: elementTypeArr,
                        name: "elementType"
                    }).on("ITEM_CLICK", function(e) {
                        self.getElementSmallCategory();
                    }).val({
                        value: '0',
                        text: I18N.getText('templateDetail', 'allElementType')
                    });

                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }
        /**
         * 添加元素dialog
         */
        this.openAddElementDialog = function() {
            $('#uploadSimpleEle').trigger('click');
        }

        /**
         * 通过颜色过滤元素
         */
        this.filterByColor = function(e) {
            var _tE = e.target;
            $(_tE).parents(".element-color-select").find(".circle").removeClass("active");
            $(_tE).addClass("active");

            var color = $(e.currentTarget).data('color');
            var param = {
                templateId: self.templateId,
                elementLevel: $(e.currentTarget).parent().parent().data('style'),
                elementType: self.$root.find('input[name="elementType"]').attr('data-val') || 0,
                color: color || 'black'
            }
            var imgContainerArea = $(e.currentTarget).parent().parent().parent().parent().next().find('ul');
            Kit.loading.show(imgContainerArea);
            http.work('/ectemplate/filter', param, 'POST').then(function(res) {
                if (res.succeed) {
                    imgContainerArea.empty();
                    var eles = [];
                    _.each(res.data, function(option) {
                        eles.push(option.parentCode);
                        var liClass = "can";
                        if (!option.elementPreview && option.elementImg){
                            liClass = "default-i can";
                        }
                        imgContainerArea.append('<li class="' + liClass + '"><div class="element-img-div" data-toggle="tooltip" title="'+ option.elementName +'"><img class="liImg" data-id="' + option.id + '" src="' + (option.elementPreview ? option.elementPreview : option.elementImg) + '" /></div></li>');
                    });
                    _.each(self.smallCategory, function(m) {
                        if ($.inArray(m.code, eles) == -1) {
                            var tempStr = "";
                            if(m.context.length >15){
                                tempStr = m.context.substr(0,15);
                                tempStr+= "...";
                            }else{
                                tempStr = m.context;
                            }
                            imgContainerArea.append('<li class="notallow"><div class="element-font-div">'+tempStr +'</div></li>');
                        }
                    });

                    self.bindLiImgActive();
                    self.adjuestElementGroup();
                    $("[data-toggle='tooltip']").tooltip();
                } else {
                    Kit.alert2(res.errorMsg);
                }
                Kit.loading.hide(imgContainerArea);
            });
        }

        /**
         * 展开此种类元素
         */
        this.findThisTypeAllElement = function(e) {
            var $swap = $(e.currentTarget);
            var fold = I18N.getText('templateDetail', 'expandAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-down"></i>';
            var unfold = I18N.getText('templateDetail', 'shrinkAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-up"></i>';
            var t = $swap.hasClass('unfold') ? fold : unfold;
            var $lis = $swap.prev().find('ul li.unActive');
            $swap.html(t);
            $swap.hasClass('unfold') ? $lis.slideUp(200) : $lis.slideDown(200);
            $swap.toggleClass('unfold');
            // self.adjuestElementGroup();
        }

        /**
         * 在模板上预览元素
         */
        this.openPreviewElementStyleDialog = function(e) {
            var param = {
                templateId: self.templateId
            }

            var fele = $(e.currentTarget).prev().prev().find('.active img').data('id'); //主要元素
            var sele = $(e.currentTarget).prev().find('.active img').data('id'); //次要元素
            var fs = self.$root.find('input[name="elementLevel"]').attr('data-val');
            if(fs == 'F') {
                if (sele) {
                    Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectHelp'));
                } else {
                    Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectMain'));
                }
                return;
            } else if (fs == 'S') {
                if (sele) {
                    Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectMain'));
                } else {
                    Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectHelp'));
                }
                return;
            }

            if (fele) {
                param.fele = fele;
            } else {
                Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectMain'));
                return;
            }
            if (sele) {
                param.sele = sele;
            } else {
                Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectHelp'));
                return;
            }
            self.$root.find('#preview-element-style').modal('show');
            var loadingArea = self.$root.find('#preview-element-style .modal-body');
            Kit.loading.show(loadingArea);
            http.work('/ectemplate/previewOnTmpl', param, 'POST').then(function(res) {
                if (res.succeed) {
                    loadingArea.html('<img src="' + res.data.preview + '" style="width:100%" />');
                } else {
                    Kit.alert2(res.errorMsg);
                }
                Kit.loading.hide(loadingArea);
            });
        }

        /**
         * 过滤刷新所有页面元素
         */
        this.filterFindElements = function() {
            var param = {
                templateId: self.templateId,
                elementLevel: self.$root.find('input[name="elementLevel"]').attr('data-val'),
                elementType: self.$root.find('input[name="elementType"]').attr('data-val') || 0,
                color: 'black'
            }
            var loadingArea = self.$root.find('.element-result-container');
            Kit.loading.show(loadingArea);
            http.work('/ectemplate/filter', param, 'POST').then(function(res) {
                if (res.succeed) {
                    //一、解析成一组一组的元素，更易于渲染页面
                    var result = _.groupBy(res.data, function(n) {
                        return n.styleGroup
                    });
                    self.$elementContainer.empty();
                    for (var p in result) {
                        var elementGroupEach = '<div class="element-group-each">';
                        //二、一组里面的 主要样式和 辅助样式分开
                        var elementGroup = _.groupBy(result[p], function(o) {
                            return o.name
                        });
                        var elementGroupArr = [];
                        for (var q in elementGroup) {
                            var smallCategoryTemp = [];      //临时存放此组样式中没有的二级分类
                            var hasTemp = [];                //此组样式包含的二级分类
                            var elementGroupList = elementGroup[q];

                            _.each(elementGroupList, function(l) {
                                hasTemp.push(l.parentCode);
                            });

                            _.each(self.smallCategory, function(m) {
                                if ($.inArray(m.code, hasTemp) == -1) {
                                    smallCategoryTemp.push(m.context);
                                }
                            });

                            elementGroupArr.push({
                                style: q,
                                category : smallCategoryTemp,
                                list: elementGroupList
                            });
                        }
                        _.each(elementGroupArr, function(el) {
                            elementGroupEach += self.initElementGroupHtml(el);
                        });

                        elementGroupEach += '<div class="element-group-preview-font"><span class="font-icon font-icon-stopu"></span>&nbsp;'+ I18N.getText('templateDetail', 'previewOnTemplate') +'</div></div>';
                        self.$elementContainer.append(elementGroupEach);

                        self.$root.find('.element-img-unfold').off('click').on('click', $.proxy(self.findThisTypeAllElement, self));
                        self.$root.find('.circle').off('click').on('click', $.proxy(self.filterByColor, self));
                        self.$root.find('.circle-black').addClass('active');
                        self.$root.find('.element-group-preview-font').off('click').on('click', $.proxy(self.openPreviewElementStyleDialog, self));
                        self.bindLiImgActive();
                    }
                    $("[data-toggle='tooltip']").tooltip();
                    self.adjuestElementGroup();
                    self.hidenUnActive();
                    $(window).resize(function() {
                        self.adjuestElementGroup();
                    });
                } else {
                    Kit.alert2(res.errorMsg);
                }
                Kit.loading.hide(loadingArea);
            });
        }

        /**
         * li元素选择交互
         */
        this.bindLiImgActive = function() {
            self.$root.find('.element-img-container ul li.can').off('click').on('click', function() {
                $(this).css('border', '1px solid #fd9611');
                $(this).siblings().css('border', '1px solid #dcdcdc');
                $(this).addClass("active").siblings().removeClass("active");
            });
        }

        /**
         * 渲染每组元素
         */
        this.initElementGroupHtml = function(el) {
            var tmpHtml = _.template(I18N.parse(elementGroupTpl, 'templateDetail'))({
                d: el
            });
            return tmpHtml;
        }

        /**
         * 调整元素中图片的显示数量
         */
        this.adjuestElementGroup = function(e) {
            self.$root.find('.element-group-each-child').each(function() {
                var $container = $(this).find('.element-img-container');
                var $unfold = $(this).find('.element-img-unfold');
                var unfoldFlag = $unfold.hasClass('unfold');
                var w = $(this).width(); //包含图片的容器宽度
                var n = Math.floor(w / 94) * 2; //显示两行的数量
                $container.find('ul li').each(function(i, v) {
                    $(this).toggleClass('unActive', i >= n);
                    if (!unfoldFlag) {
                        $(this).hasClass('unActive') ? $(this).hide() : $(this).show();
                    }
                });
            });


            self.$root.find('.element-img-container').each(function() {
                var width = $(this).width() - 1; //外面容器的宽度.
                var n = Math.floor(width / 94); //显示1行的数量
                var w = 82 * n; //每个元素84px
                var marginRight = (width - w) / (n - 1); //margin-right的值,最后一个为0;
                $(this).find('ul li').css('margin-right', marginRight + 'px');
                $(this).find('ul li:nth-child(' + n + 'n)').css('margin-right', '0px');
            })


        }

        this.hidenUnActive = function() {
            self.$root.find('li.unActive').hide();
        }

        /**
         * 直接弹出上传表意元素框
         */
        this.uploadSimpleEle = function() {
            var formData = new FormData($('#uploadSimpleEleForm')[0]);
            $.ajax({
                url: apiUrl + "/ecelement/upload?templateId="+self.templateId,
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false,
                success: function(result) {
                    Kit.alert_success(I18N.getText('elementList', 'uploadSuccess'));
                    self.filterFindElements();
                },
                error: function(result) {
                    console.info(result);
                },
                data: formData,
                xhrFields: {
                    withCredentials: true
                }
            });
        }

    }
    return new SimpleElement();
});